package com.ttbj.timer.service.achieved.impl;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.DelayQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ttbj.constant.order.DelayTimeEnum;
import com.ttbj.timer.cache.AchievedRedisService;
import com.ttbj.timer.po.AchievedOrder;
import com.ttbj.timer.service.achieved.AchievedService;
import com.ttbj.timer.service.achieved.OnAchieveListener;

@Service
public class AchievedServiceImpl implements AchievedService {

	private static final Logger log = LoggerFactory.getLogger(AchievedServiceImpl.class);
	private boolean start;
	private volatile DelayQueue<AchievedOrder> delayQueue = new DelayQueue<AchievedOrder>();

	@Autowired
	private AchievedRedisService achievedRedisService = null;

	@Override
	public void start(OnAchieveListener listener) {
		if (start) {
			return;
		}
		log.error("DelayService 启动");
		start = true;
		new Thread(new Runnable() { // 子线程处理
			@Override
			public void run() {
				try {
					while (true) {
						if (delayQueue.isEmpty()) {
							continue;
						}
						AchievedOrder order = delayQueue.take();
						log.info("队列弹出的数据:{}", order);
						if (listener != null) {
							listener.onDelayedAchieve(order);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		}).start();
	}

	@Override
	public void add(AchievedOrder order) {
		if (null == order) {
			return;
		}
		achievedRedisService.setCollection(order);
		delayQueue.put(order);
	}

	@Override
	public boolean remove(AchievedOrder order) {
		if (null == order) {
			return false;
		}
		achievedRedisService.delElement(order.getOrderId());
		return delayQueue.remove(order);
	}

	@Override
	public void add(Long orderId) {
		if (null == orderId) {
			return;
		}
		log.info("队列添加元素");
		achievedRedisService.setElement(orderId);
		delayQueue.put(new AchievedOrder(orderId, DelayTimeEnum.DELAYED_ACIHEVE.getMill()));
		log.info("元素:{}", delayQueue.toString());
	}

	@Override
	public void remove(Long orderId) {
		if (null == orderId) {
			return;
		}
		AchievedOrder[] array = delayQueue.toArray(new AchievedOrder[] {});
		if (array == null || array.length <= 0) {
			return;
		}
		List<AchievedOrder> orders = Arrays.asList(array);
		AchievedOrder other = orders.stream().filter(order -> order != null).filter(order -> orderId.equals(order.getOrderId())).findAny().orElse(null);
		log.info("过滤后的订单:{}", other);
		if (null == other) {
			return;
		}
		remove(other);
	}

	@Override
	public DelayQueue<AchievedOrder> convertQueue() {
		delayQueue = achievedRedisService.getQueue();
		log.info("队列:{}", delayQueue.toString());
		return delayQueue;
	}

}
